<?php

namespace App\Http\Controllers\Guard\User;

use App\Http\Controllers\Common\GuardController;
use App\Models\Constant\Constant;
use App\Models\Setting\SysSetting;
use App\Models\User\MemberOrder;
use App\Models\User\SeeLog;
use App\Models\User\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserController extends GuardController {

    public function seeLog(Request $request) {
        $days = [];
        foreach (range(0, 9) as $num) {
            $days[] = date('Y-m-d',strtotime("-$num day"));
        }
        $records = SeeLog::query()->whereIn('day', $days)->get();
        $userIds = $records->pluck('user_id')->unique()->toArray();
        $users = User::query()->whereIn('id', $userIds)->get();
        $datas = [];
        $index = 1;
        foreach ($userIds as $userId) {
            $temp = [];
            $logs = $records->where('user_id',$userId);
            //if($logs->count()<10)continue;//10天内总查阅次数小于10篇的不统计
            $temp['count'] = $logs->count();
            $user = $users->where('id',$userId)->first();
            $temp['userId'] = $user->id;
            $temp['avatar'] = $user->avatar;
            $temp['nick_name'] = $user->nick_name;
            $temp['logs'] = [];
            foreach ($days as $day) {
                $dayCount = $logs->where('day',$day)->count();
                if($dayCount==0)continue;//单天查阅次数小于10篇的不统计
                $temp['logs'][] = $day.':'.$dayCount;

            }
            $temp['logs'] = implode('|',$temp['logs']);
            if(count($temp)>0)
                $datas[] = $temp;
        }
        array_multisort(array_column($datas, 'count'),SORT_DESC,$datas);
        foreach ($datas as &$data) {
            $data['id'] = $index++;
            //$data['count'] = count($days).'天内，总观看次数'.$data['count'];
        }

        return responseSuccess($datas);
    }


    public function lst(Request $request) {
        $mapMemberType = SysSetting::whereIn('key',['first','month','quarter','year'])->pluck('item_desc','key')->toArray();
        $exMapMemberType = SysSetting::whereIn('key',['exfirst','exmonth','exquarter','exyear'])->pluck('item_desc','key')->toArray();

        $conditions = $request->input();
        $records = (new User())->getLst($conditions)
            ->withCount(['getDownloadWord','getDownloadPpt'])
            ->paginate($conditions['pageSize']??30,['*'],'page',$conditions['page']??1);
        foreach ($records as $record) {
            $record->download_word = $record->get_download_word_count;
            $record->download_ppt = $record->get_download_ppt_count;
            $record->member_type_name = $mapMemberType[$record->type]??'普通用户';
            $record->buy_time = '';
            if($record->is_member==1){
                //最近一次订单主网站订单
                $order = $record->getUserLastOrder(1);
                $record->buy_time = empty($order)?'':date('Y-m-d H:i:s',strtotime($order->created_at));
            }

            $record->ex_buy_time = '';
            $record->ex_member_type_name = $exMapMemberType[$record->ex_type]??'普通用户';
            if($record->ex_is_member==1){
                //最近一次订副主网站订单
                $order = $record->getUserLastOrder(3);
                $record->ex_buy_time = empty($order)?'':date('Y-m-d H:i:s',strtotime($order->created_at));
            }
        }

        return responseSuccess($records->items(),$records->total());
    }

    public function memberLst(Request $request) {
        $mapMemberType = SysSetting::whereIn('key',['first','month','quarter','year'])->pluck('item_desc','key')->toArray();
        $mapMemberType['exfirst'] = '副首试('.Constant::ExFirstDay.'天)';
        $mapMemberType['exmonth'] = '副月卡';
        $mapMemberType['exquarter'] = '副季卡';
        $mapMemberType['exyear'] = '副年卡';
        $conditions = $request->input();
        $records = (new MemberOrder())->newQuery()->where('is_finished',1);
        if(!empty($conditions['account'])){
            $records = $records->whereHas('getUser',function ($q) use ($conditions) {
                $q->where('nick_name','like','%'.$conditions['account'].'%') ;}
            );
        }
        if(!empty($conditions['phone'])){
            $records = $records->whereHas('getUser',function ($q) use ($conditions) {
                $q->where('phone',$conditions['phone']) ;}
            );
        }
        $records = $records->with('getUser')->orderByDesc('id')->paginate($conditions['pageSize']??30,['*'],'page',$conditions['page']??1);
        foreach ($records as $record) {
            $record->member_type_name = $mapMemberType[$record->type]??'普通用户';
            if($record->getUser->ex_is_member==1){
                $record->user_expire_time = $record->getUser->ex_expire_time;
            }else{
                $record->user_expire_time = $record->getUser->expire_time;
            }
        }
        return responseSuccess($records->items(),$records->total());
    }

    public function add(Request $request) {
        $info = $request->input();
        $id = $request->input('id',0);
        //dd($conditions);

        if(isset($info['expireTime'])){
            $info['expire_time'] = $info['expireTime'];
            unset($info['expireTime']);
        }

        $user = User::updateOrCreate(compact('id'),$info);
        return responseSuccess($user->toArray());
    }

    public function detail(Request $request) {
        $ids = $request->input('ids','');
        return $this->getRecordByIds(User::class, $ids);
    }

    public function del(Request $request) {
        $ids = $request->input('ids','');
        return $this->delRecords(User::class, $ids);
    }

    public function setMember(Request $request){

        $userId = $request->input('id');
        $type = $request->input('type');

        $user = User::where(['id'=>$userId])->first();
        if(empty($user)){return responseFail('未查找到有用户！');}

        if($type=='first' && $user->isBuyFirst()) {return responseFail('您已经购买过首试了！');}

        $mapMemberType = SysSetting::whereIn('key',['first','month','quarter','year'])
            ->pluck('val','key')->toArray();
        $fee = $mapMemberType[$type];

        //如果是会员，从过期时间开始计算，如果是非会员，从当前时间开始计算
        $expire_time = $user->is_member==1?Carbon::parse($user->expire_time):Carbon::now();
        if($type=='first'){
             $expire_time = $expire_time->addDays(30)->toDateTimeString();
        }elseif ($type=='month'){
            $expire_time = $expire_time->addMonths()->toDateTimeString();
        }elseif ($type=='quarter'){
            $expire_time = $expire_time->addQuarters()->toDateTimeString();
        }elseif ($type=='year'){
            $expire_time = $expire_time->addYears()->toDateTimeString();
        }else{
            return responseFail('会员类型错误！');
        }
        try {
            DB::beginTransaction();
            $user->is_member = 1;
            $user->ex_type = $type;
            $user->expire_time = $expire_time;
            $user->save();

            MemberOrder::create(['user_id'=>$userId,'order_number'=>time().uniqid(),'fee'=>$fee,'type'=>$type,
                'is_finished'=>1,'is_auto'=>2]);
            DB::commit();
            return responseSuccess();
        } catch (\Exception $e) {
            DB::rollBack();
            $tip = $e->getFile() . ':' . $e->getLine() . ':' . $e->getMessage();
            Log::error($tip);
            return responseFail($tip);
        }
    }

    public function setExMember(Request $request){

        $id = $request->input('id');
        $ex_type = $request->input('type');
        $mapMemberType = SysSetting::whereIn('key',['exfirst','exmonth','exquarter','exyear'])
            ->pluck('val','key')->toArray();
        $fee = $mapMemberType[$ex_type]??0;
        if($fee==0)return responseFail('价格错误！');

        $user = User::where(compact('id'))->first();
        if(empty($user)){
            return responseFail('未查找到有用户！');
        }
        if($ex_type=='exfirst' && $user->isExBuyFirst()) {
            return responseFail('您已经购买过'.Constant::ExFirst.'次首试了！');
        }
        $ex_expire_time = $user->ex_is_member==1?Carbon::parse($user->ex_expire_time):Carbon::now();
        if($ex_type=='first'){
            $ex_expire_time = $ex_expire_time->addDays(30)->toDateTimeString();
        }elseif ($ex_type=='month'){
            $ex_expire_time = $ex_expire_time->addMonths()->toDateTimeString();
        }elseif ($ex_type=='quarter'){
            $ex_expire_time = $ex_expire_time->addQuarters()->toDateTimeString();
        }elseif ($ex_type=='year'){
            $ex_expire_time = $ex_expire_time->addYears()->toDateTimeString();
        }else{
            return responseFail('会员类型错误！');
        }
        try {
            DB::beginTransaction();
            $user->ex_is_member = 1;
            $user->ex_type = $ex_type;
            $user->expire_time = $ex_expire_time;
            $user->save();
            MemberOrder::create(['user_id'=>$id,'order_number'=>time().uniqid(),'fee'=>$fee,'type'=>$ex_type,
                'is_finished'=>1,'is_auto'=>3]);
            DB::commit();
            return responseSuccess();
        } catch (\Exception $e) {
            DB::rollBack();
            $tip = $e->getFile() . ':' . $e->getLine() . ':' . $e->getMessage();
            Log::error($tip);
            return responseFail($tip);
        }
    }

    public function setPhonePwd(Request $request) {
        $id = $request->input('id');
        $phone = $request->input('phone');
        $pwd_content = $request->input('pwd');
        $pwd = md5($pwd_content);
        User::where('id',$id)->update(compact('phone','pwd_content','pwd'));
        return responseSuccess();

    }
}
